import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import { Menu, Icon, Button } from "antd";
import menuList from "../../config/menuConfig";
import storeutils from "../../util/storeutil";
const { SubMenu } = Menu;
class Leftnav extends Component {
  hasAuth = (item) => {
    const { key, isPublic } = item;
    const menus = storeutils.getUser().role.menus;
    console.log(menus);
    const username = storeutils.getUser().username;
    if (username === "admin" || isPublic || menus.indexOf(key) !== -1) {
      return true;
    } else if (item.children) {
      return !!item.children.find((child) => {
        menus.indexOf(child.key) !== -1;
      });
    }
    return false;
  };
  getMenuNodes_map = (menulist) => {
    const path = this.props.location.pathname;
    return menulist.map((item) => {
      if (this.hasAuth(item)) {
        if (!item.children) {
          return (
            <Menu.Item key={item.key}>
              <Link to={item.key}>
                <Icon type={item.icon} />
                <span>{item.title}</span>
              </Link>
            </Menu.Item>
          );
        } else {
          const cItem = item.children.find(
            (cItem) => path.indexOf(cItem.key) === 0
          );
          if (cItem) {
            // 根据路由去匹配此路由在路由表中的父路由
            // 说明匹配上了
            this.openKey = item.key;
          }
          return (
            <SubMenu
              key={item.key}
              title={
                <span>
                  <Icon type={item.icon} />
                  <span>{item.title}</span>
                </span>
              }
            >
              {/* 递归调用自己 */}
              {this.getMenuNodes_map(item.children)}
            </SubMenu>
          );
        }
      }
    });
  };
  componentWillMount() {
    this.menuNodes = this.getMenuNodes_map(menuList);
  }
  render() {
    const path = this.props.location.pathname;
    const openKey = this.openKey;
    console.log(openKey);
    return (
      <div>
        <Menu
          selectedKeys={[path]}
          defaultOpenKeys={[openKey]}
          mode="inline"
          theme="dark"
        >
          {this.menuNodes}
        </Menu>
      </div>
    );
  }
}

export default withRouter(Leftnav);
